<template>
  <div class="add-container" :style="{ '--local-mount-height': cssVar ? `var(${cssVar})` : '100%' }" ref="scrollerRef">
    <div class="directory-selector">
      <el-select v-model="state.openPath" placeholder="选择输出目录" @change="handleScanImage">
        <el-option
          v-for="path in state.outPutPath"
          :key="path"
          :label="path"
          :value="path"
        />
      </el-select>
      <el-button class="ml10" type="primary" @click="handleChangeOutputPath">打开目录</el-button>
    </div>

    <Waterfall
      :items="state.imageList"
      :isLoading="state.isLoadingMore"
      :isComplete="!state.hasMore"
    />

    <!-- 滚动检测点 -->
    <div ref="sentinelRef" style="height: 1px; width: 100%;"></div>
  </div>
</template>

<script setup lang="ts" name="ImagePanel">
import { ipcService } from '@renderer/services/ipcService';
import { useConfigStore } from '@renderer/stores/configStore';
import { useModelStore } from '@renderer/stores/useModelStore';
import { defineAsyncComponent, getCurrentInstance, onMounted, onUnmounted, reactive, ref } from 'vue';

const instance = getCurrentInstance();
const cssVar = instance?.appContext.config.globalProperties.$cssVarName;
const modelStore = useModelStore()
const configStore = useConfigStore()
const scrollerRef = ref()
const sentinelRef = ref<HTMLElement>()
const observer = ref<IntersectionObserver>()

const state = reactive({
  openPath: '',
  outPutPath: [] as string[],
  imageList: [] as any[],
  allImages: [] as any[],
  currentPage: 1,
  pageSize: 20,
  isLoadingMore: false,
  hasMore: true
})

const Waterfall = defineAsyncComponent(() => import('./component/WaterFall.vue'))

// 图片扫描处理
const handleScanImage = async (path: string) => {
  try {
    const result = await ipcService.scanImages(modelStore.outputPath, path)
    if (result?.success) {
      state.allImages = result.images
      state.currentPage = 1
      state.imageList = []
      // 修复：只要存在图片就设置为true
      state.hasMore = state.allImages.length > 0
      if(state.allImages.length > 0){
        loadMoreImages()
      }
    }
  } catch (error) {
    console.error('扫描图片失败:', error)
  }
}

// 加载更多图片
const loadMoreImages = () => {
  if (state.isLoadingMore || !state.hasMore) return

  state.isLoadingMore = true
  const start = (state.currentPage - 1) * state.pageSize
  // 修复：确保end不超过数组长度
  const end = Math.min(start + state.pageSize, state.allImages.length)

  // 修复：添加类型检查
  const newImages = state.allImages.slice(start, end).map((path, index) => ({
    id: start + index,
    title: typeof path === 'string' ? path : path.name || '',
    url: typeof path === 'string' ? path : path.path || '',
    placeholder: getPlaceholder(1.5),
    aspectRatio: 1.5
  }));

  state.imageList = [...state.imageList, ...newImages]
  state.currentPage++
  // 修复：正确判断是否还有更多数据
  state.hasMore = end < state.allImages.length
  state.isLoadingMore = false
}

// 生成占位符SVG
function getPlaceholder(aspectRatio: number): string {
  const width = 10;
  const height = Math.round(width * aspectRatio);
  return `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${width} ${height}'%3E%3C/svg%3E`;
}

// 初始化目录扫描
const initOutputPaths = async () => {
  try {
    const result = await ipcService.scanDirectories(configStore.config.outputPath)
    if (result?.success) {
      // 检查返回的目录数组是否为空
      state.outPutPath = result.directories.length > 0
        ? result.directories
        : [configStore.config.outputPath] // 为空时使用配置的默认路径
    } else {
      // API调用成功但返回失败状态，使用默认路径
      state.outPutPath = [configStore.config.outputPath]
    }
  } catch (error) {
    console.error('初始化目录失败:', error)
    // 捕获错误时也使用默认路径
    state.outPutPath = [configStore.config.outputPath]
  }
}

const handleChangeOutputPath = async () => {
  await configStore.handleSelectOutputPath()
  await initOutputPaths()
  if (state.outPutPath.length > 0) {
    state.openPath = state.outPutPath[0]
    handleScanImage(state.openPath)
  }
}

// 初始化
onMounted(() => {
  initOutputPaths()
  if (modelStore.outputPath) {
    handleScanImage(modelStore.outputPath)
  }

  // 设置滚动监听
  observer.value = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting && !state.isLoadingMore && state.hasMore) {
      loadMoreImages()
    }
  }, { root: scrollerRef.value, threshold: 0.1 })

  if (sentinelRef.value) {
    observer.value.observe(sentinelRef.value)
  }
})

onUnmounted(() => {
  if (observer.value) {
    observer.value.disconnect()
  }
})
</script>

<style scoped>
.add-container {
  height: calc(var(--local-mount-height) - 85px);
  overflow: auto;
  padding: 20px;
}

.directory-selector {
  margin-bottom: 20px;
  max-width: 600px;
  display: flex;
}
</style>
